import { FC, useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { observer, useLocalStore } from 'mobx-react';
import { Steps, Button, Space } from 'antd';

import { resetPasswordStore } from '@/stores/ResetPassword';

import styles from './ResetPasswordFlow.module.less';
import SureAccountForm from './Form/SureAccountForm';
import ResetPasswordForm from './Form/ResetPasswordForm';
import CompleteForm from './Form/CompleteForm';

const steps = [
  {
    key: 'first',
    title: '确认账户',
    content: <SureAccountForm />
  },
  {
    key: 'second',
    title: '重置密码',
    content: <ResetPasswordForm />
  },
  {
    key: 'last',
    title: '完成',
    content: <CompleteForm />
  }
];

const ResetPasswordFlow: FC = () => {
  const [current, setCurrent] = useState<number>(0);
  const store = useLocalStore(() => resetPasswordStore);

  const navigate = useNavigate();

  /** 取消|确认 */
  const handleCancelOrOk = useCallback(() => {
    // 点取消|确认时, 清除记录的表单信息
    store.sureAccountFormInitValues = {};
    navigate('/oauth/login', { replace: true });
  }, []);

  /** 下一步 */
  const handleNext = useCallback(async () => {
    if (!current) {
      // 确认账户界面
      const fields = await store.sureAccountForm?.validateFields();
      // 设置点击上一步返回到 确认账号 页面表单的默认值
      store.sureAccountFormInitValues = { username: fields.username, email: fields.email };
      setCurrent(current + 1);
    } else {
      // 重置密码界面
      const fields = await store.resetPasswordForm?.validateFields();
      // 此时点击下一步即调用接口重置账户密码
      // const res = await resetPassword({ ...sureAccountFormInitValues, ...fields });
      if (fields) setCurrent(current + 1);
    }
  }, [current]);

  /** 上一步 */
  const handlePrev = useCallback(() => {
    setCurrent(current - 1);
  }, [current]);

  return (
    <div className={styles.rbFpFlowContent}>
      <div className={styles.rbFpFlowStepsContent}></div>
      <Steps current={current} items={steps} />
      <div className={styles.rbFpFlowFormContent}>{steps[current].content}</div>
      <div className={styles.rbFpFlowActionContent}>
        <Space>
          {!current && (
            <Button style={{ width: '10rem' }} onClick={handleCancelOrOk}>
              取消
            </Button>
          )}
          {current > 0 && current !== steps.length - 1 && (
            <Button style={{ width: '10rem' }} onClick={handlePrev}>
              上一步
            </Button>
          )}
          {current < steps.length - 1 && (
            <Button type="primary" style={{ width: '10rem' }} onClick={handleNext}>
              下一步
            </Button>
          )}
          {current === steps.length - 1 && (
            <Button type="primary" style={{ width: '10rem' }} onClick={handleCancelOrOk}>
              去登录
            </Button>
          )}
        </Space>
      </div>
    </div>
  );
};

export default observer(ResetPasswordFlow);
